package com.stefanini.worldcupinformation.filters;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SecurityFilter implements Filter {
    
    public static final String LOGGED_USER = "LOGGED_USER";
    public static final String IS_LOGGED = "IS_LOGGED";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            HttpSession session = request.getSession(false);
            
            boolean validUser = false;
            if(session != null){
                Boolean isLoggedIn = (Boolean) session.getAttribute(IS_LOGGED);
                if(Boolean.TRUE.equals(isLoggedIn)){
                    validUser = true;
                }
            }
            
            if(validUser){
                chain.doFilter(req, resp);
            }else{
                if(session != null){
                    session.invalidate();
                }
                response.sendRedirect("/worldCupInformation/login.xhtml");
            }
        } catch (IOException | ServletException e) {
            Logger.getLogger(SecurityFilter.class.getName()).log(Level.SEVERE,"Error en el filtro de seguridad", e);
        }
    }

    @Override
    public void destroy() {
        
    }
    
}
